package org.apache.ibatis.demo;

import org.apache.ibatis.demo.bean.User;
import org.apache.ibatis.demo.generator.BankCardGenerator;
import org.apache.ibatis.demo.generator.IdCardGenerator;
import org.apache.ibatis.demo.generator.NameGenerator;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.Random;

public class BatchInsertDemo {

    public static void main(String[] args) throws Exception {
        // 定义资源文件
        InputStream resource = Resources.getResourceAsStream("org\\apache\\ibatis\\demo\\conf\\mybatis.xml");
        // 根据配置配置文件构建会话工厂
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resource);
        // 开启会话
        SqlSession sqlSession = sqlSessionFactory.openSession();
        // 生成user对象
        List<User> users = new LinkedList<>();
        for (int i = 0; i < 2; i++) {
            users.add(randomUser());
        }

        // mapper方式执行
        int count = sqlSession.getMapper(UserDao.class).batchInsert(users);
        System.out.println("Batch insert count : " + count);
        users.forEach(System.out::println);

    }

    /**
     * 随机生成User
     *
     * @return user
     */
    private static User randomUser() {
        User user = new User();
        user.setName(NameGenerator.randomChineseName());
        user.setIdCard(IdCardGenerator.randomIdCard());
        user.setBankCard(BankCardGenerator.randomBankCard());
        user.setGender(new Random().nextInt(2));
        return user;
    }

}
